import compose from "./compose";

/**
 * 
 * @param  {...any} middlewares 中间件
 */
export default function applyMiddleware ( ...middlewares ) {
  return ( createStore ) => {
    return ( reducer, initState ) => {
      let dispatch
      // 创建Store实例
      const store = createStore( reducer, initState );
      // 封存中间件API
      const middlewareAPI = {
        getState: store.getState,
        dispatch: (action) => dispatch(action) // 加强后的dispatch
      };
      // 揭开中间第一层(封存原始的store)
      // BUG:如果在中间件直接调用第一层的dispatch，会造成死循环
      const chain = middlewares.map(middleware => middleware(middlewareAPI));
      // 增强后的dispatch(揭开中间第二层)
      dispatch = compose(...chain)(store.dispatch)
      // 第三层用户去触发
      return { ...store, dispatch } 
    }
  }
}